package org.su.webadapter.bind;


import org.su.generalmvc.IEditor;
import org.su.generalmvc.core.InitialContext;
import org.su.generalmvc.entity.PojoCache;
import org.su.generalmvc.entity.ProtobufCache;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public final class PMessageEditor implements IEditor {

	@Override
	public Object getParamValue(String paramName, Class<?> paramType, int paramIndex, Method writer,
			ServletRequest request, ServletResponse response) {
		try {
			ProtobufCache pc = (ProtobufCache)InitialContext.getInstance().getContext().getPojoContext().get(paramType.getName());
			if(pc == null){
				return null;
			}
			Object obj = pc.getNewBuilder().invoke(paramType);
			String prifix = paramName + ".";
			List<String> names = pc.getMethodNames();
			Object value = null;
            String name = null;
			for(int i=0;i<names.size();i++){
                name = prifix + names.get(i);
				if(request.getParameter(name) != null){
					value = pc.getEditors().get(i).getParamValue(name,	paramType,	paramIndex, writer,
							request, response);
					if(value!=null){
						pc.getMethods().get(i).invoke(obj, value);
					}
				}
			}

            value = null;
            names = null;
            name = null;
            prifix = null;
			paramType = null;

            return pc.getBuild().invoke(obj);

		} catch (Exception e) {
			throw new ParamBindException(e, "param name is :" + paramName);
		}
	}


}
